package com.media.entrance.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.media.entrance.config.CustomParameters;
import com.media.entrance.model.MatchAndResourceModel;
import com.media.entrance.service.MediaCustomerService;
import com.media.entrance.service.MediaResourceManageService;
import com.media.entrance.utils.MediaEntranceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

//一期，仅实时音视频层接口
@Controller
@Slf4j
@RequestMapping("/customer")
@Deprecated
public class CustomerController {

    @Autowired
    private MediaCustomerService mediaCustomerService;
    @Autowired
    private MediaResourceManageService mediaResourceManageService;

    @Autowired
    private CustomParameters customParameters;

    String DeviceIdTagName;
    String AgentIdTagName;
    String RoomIdTagName;
    String QueueNoTagName;
    Boolean IsAgentReady;
    String RequestRouterTagName;
    String ForwarderTagName;
    String RecorderTagName;
    String ForwarderServiceName;
    String RecorderServiceName;
    int RedisKeepTimeout;

    private void setTempParameters(CustomParameters customParameters){
        if (customParameters == null) {
            DeviceIdTagName = "deviceId";
            AgentIdTagName = "agentId";
            RoomIdTagName = "roomId";
            QueueNoTagName = "queueNo";
            IsAgentReady = true;
            RequestRouterTagName = "isRequestRouter";
            ForwarderTagName = "forwarderInfo";
            RecorderTagName = "recorderInfo";
            ForwarderServiceName = "forwarder-service";
            RecorderServiceName = "recorder-service";
            RedisKeepTimeout = 5;
            return;
        }
        DeviceIdTagName = customParameters.getDeviceIdTagName();
        AgentIdTagName = customParameters.getAgentIdTagName();
        RoomIdTagName = customParameters.getRoomIdTagName();
        QueueNoTagName = customParameters.getQueueNoTagName();
        IsAgentReady = customParameters.isAgentReady();
        RequestRouterTagName = customParameters.getRequestRouterTagName();
        ForwarderTagName = customParameters.getForwarderTagName();
        RecorderTagName = customParameters.getRecorderTagName();
        ForwarderServiceName = customParameters.getForwarderServiceName();
        RecorderServiceName = customParameters.getRecorderServiceName();
        RedisKeepTimeout = customParameters.getRedisKeepTimeout();
    }
    @ResponseBody
    @RequestMapping(value = "/getMediaResource", method = RequestMethod.POST)
    public MatchAndResourceModel getMediaResource(@RequestBody JSONObject jsonParam) {
        log.info("getMediaResource receive jsonobject: " +  jsonParam.toJSONString());
        setTempParameters(customParameters);
        // 获取报文中的设备Id 拼接房间id
        if (!jsonParam.containsKey(DeviceIdTagName)) {
            throw new MediaEntranceException(DeviceIdTagName + "deviceId is null");
        }
        String deviceId = jsonParam.getString(DeviceIdTagName);

        if (!jsonParam.containsKey(RoomIdTagName)) {
            throw new MediaEntranceException(RoomIdTagName + "roomId is null");
        }
        String roomId = jsonParam.getString(RoomIdTagName);
        if (!jsonParam.containsKey(AgentIdTagName)) {
            throw new MediaEntranceException(AgentIdTagName + "agent is null");
        }
        String agentId = jsonParam.getString(AgentIdTagName);

        MatchAndResourceModel matchInfo = new MatchAndResourceModel();
        matchInfo.setDeviceId(deviceId);
        matchInfo.setRoomId(roomId);
        matchInfo.setAgentId(agentId);

        mediaResourceManageService.getMediaServiceResource(matchInfo);
        log.info("match a agent: " + matchInfo);
        return matchInfo;
    }

    // 旧接口
    @ResponseBody
    @RequestMapping(value = "/getMediaResourceOld", method = RequestMethod.POST)
    public String getMediaResourceOld(@RequestBody JSONObject jsonParam) {
        log.info("customerController from nacos: " +  customParameters.toString());
        setTempParameters(customParameters);
        log.info("getMediaResource receive jsonobject: " +  jsonParam.toJSONString());

        // 获取报文中的设备Id 拼接房间id
        if (!jsonParam.containsKey(DeviceIdTagName)) {
            throw new MediaEntranceException(DeviceIdTagName + "deviceId is null");
        }
        String deviceId = jsonParam.getString(DeviceIdTagName);

        if (!jsonParam.containsKey(RoomIdTagName)) {
            throw new MediaEntranceException(RoomIdTagName + "roomId is null");
        }
        String roomId = jsonParam.getString(RoomIdTagName);

        String redisResult = mediaCustomerService.getFromRedis(roomId);
        log.info("getMediaResource get redis roomId: [" +  roomId + "]:redisResult:" +redisResult);

        // 标志位，判断是转发还是录像需要更新
        boolean needForwarderRedistribute = true;
        boolean needRecorderRedistribute = true;
        if (redisResult != null) {
//            if (jsonParam.containsKey("needRedistribute")) {
//                boolean needRedistribute = jsonParam.getBoolean("needRedistribute");
//                if (needRedistribute) {
//                    // 如果需要更新，则重新获取标志位，判断是转发还是录像需要更新
//                    needForwarderRedistribute = mediaCustomerService.needRedistribute(redisResult, ForwarderTagName, ForwarderServiceName);
//                    needRecorderRedistribute = mediaCustomerService.needRedistribute(redisResult, RecorderTagName, RecorderServiceName);
//                } else {
//                    return redisResult;
//                }
//            } else {
//                return redisResult;
//            }

            // 如果需要更新，则重新获取标志位，判断是转发还是录像需要更新
            needForwarderRedistribute = mediaCustomerService.needRedistribute(redisResult, ForwarderTagName, ForwarderServiceName);
            needRecorderRedistribute = mediaCustomerService.needRedistribute(redisResult, RecorderTagName, RecorderServiceName);
            if (!needForwarderRedistribute && !needRecorderRedistribute ) {
                return redisResult;
            }
        }
        // 找一个转发服务，如果转发需要更新则更新
        JSONObject forwarderInfo = addServiceInfo(needForwarderRedistribute, ForwarderTagName, ForwarderServiceName, RedisKeepTimeout, redisResult);
        // 找一个录像服务，如果录像需要更新则更新
        JSONObject recorderInfo = addServiceInfo(needRecorderRedistribute, RecorderTagName, RecorderServiceName, RedisKeepTimeout, redisResult);

        String agentId = null;
        JSONObject result = new JSONObject();
        result.put(RoomIdTagName, roomId);
        result.put(DeviceIdTagName, deviceId);

        // 获取报文中的请求路由的标志
        if (jsonParam.containsKey(RequestRouterTagName) && jsonParam.getBoolean(RequestRouterTagName)) {
            // 找路由模块获取坐席信息
            JSONObject agentInfo = mediaCustomerService.getAgentInfo(true);
            // 如果没有匹配到柜员，则返回排队信息
            if (agentInfo.getString(AgentIdTagName) == null) {
                result.put(DeviceIdTagName, agentInfo.getIntValue(QueueNoTagName));
                result.put(AgentIdTagName, null);
                log.info("get no agent return : [" +  result.toJSONString() + "]");
                return result.toJSONString();
            }
        } else {
            agentId = jsonParam.getString(AgentIdTagName);
            if (agentId == null) {
                throw new MediaEntranceException("deviceId or roomId is null");
            }
        }
        result.put(AgentIdTagName, agentId);
        result.put(ForwarderTagName, forwarderInfo);
        result.put(RecorderTagName, recorderInfo);

        mediaCustomerService.setInfoRedis(roomId, result.toJSONString(), 0);
        log.info("getMediaResource return result : [" +  result.toJSONString() + "]");
        return result.toJSONString();
    }

    // 处理获取新的服务信息 或从redis里取旧的信息
    private JSONObject addServiceInfo(boolean needRedistributeflag, String tagKey, String serviceName, int redisKeepTimeout, String redisResult) {
        JSONObject serviceInfo = new JSONObject();
        if (redisResult != null) {
            serviceInfo = JSON.parseObject(redisResult).getJSONObject(tagKey);
            log.info("getMediaResource get redis " + serviceName + ": [" +  serviceInfo.toJSONString() + "]");
        }
        if (needRedistributeflag) {
            serviceInfo = mediaCustomerService.getMediaServiceInfo(tagKey, serviceName, redisKeepTimeout);
            log.info("getMediaResource get new " + serviceName + ": [" +  serviceInfo.toJSONString() + "]");
        }
        return serviceInfo;
    }

    @ResponseBody
    @RequestMapping(value = "/releaseMediaResource", method = RequestMethod.POST)
    public String releaseMediaResource(@RequestBody JSONObject jsonParam) {
        log.info("customerController from nacos: " +  customParameters.toString());
        setTempParameters(customParameters);
        log.info("releaseMediaResource recevie jsonobject: " +  jsonParam.toJSONString());
        // 获取报文中的设备Id 拼接房间id
        String deviceId = jsonParam.getString(DeviceIdTagName);
        String roomId = jsonParam.getString(RoomIdTagName);
        if (deviceId == null || roomId == null) {
            throw new MediaEntranceException("deviceId or roomId is null");
        }
        Boolean result = false;
        String redisResult = mediaCustomerService.getFromRedis(roomId);
        log.info("releaseMediaResource getRedisResult receive : [" +  roomId + "]:" +redisResult);
        if (redisResult != null) {
            result = mediaCustomerService.clearKeyInRedis(roomId);
        }
        //未考虑释放路由的情况，后续考虑
        Map<String, Object> map = new HashMap<>();
        map.put("result", result);
        return (new JSONObject(map)).toJSONString();

    }
}
